package com.fifth.sso.relam;


import com.fifth.common.pojo.entity.EmpInfo;
import com.fifth.sso.feign.EmpFeign;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @program: qy151-springboot-shiro
 * @description:
 * @author: 闫克起2
 * @create: 2022-08-05 11:14
 **/
public class EmpRealm extends AuthorizingRealm {

    @Autowired
    private EmpFeign empFeign;

    @Override
    public String getName() {
        return LoginType.EMP_PHONE.getType();
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        if (token instanceof UserToken) {
            return ((UserToken) token).getLoginType() == LoginType.EMP_PHONE;
        } else {
            return false;
        }
    }

    @Override
    public void setAuthorizationCacheName(String authorizationCacheName) {
        super.setAuthorizationCacheName(authorizationCacheName);
    }

    @Override
    protected void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    //什么时候执行该方法: 当你进行权限校验时会执行该方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    //认证代码
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取登录账号
        String username = authenticationToken.getPrincipal().toString();

        //2.根据账号查询用户信息--远程调用权限微服务接口
        EmpInfo empInfo = empFeign.findByPhone(username);

        //3.判断用户是否存在
        if(empInfo!=null){
            //4.判断密码是否正确
            ByteSource salt=ByteSource.Util.bytes(empInfo.getSalt());
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(empInfo,empInfo.getPassword(),salt,this.getName());
            return info;
        }
        return null;
    }
}
